package ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;

import javax.swing.JPanel;

import model.Game;
import model.Score;

@SuppressWarnings("serial")
public class GamePanel extends JPanel {
	
	private static final String OVER = "Game Over!";
	private static final String REPLAY = "R to replay";
	private Game game;
	private Score score;
	
	public GamePanel(Game g, Score s) {
		setPreferredSize(new Dimension(Game.WIDTH, Game.HEIGHT));
		setBackground(Color.BLACK);
		this.game = g;
		this.score = s;
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		
		drawGame(g);
		drawScore(g);
		
		if (game.isOver()) {
			gameOver(g);
		}
	}
	
	private void drawGame(Graphics g) {
		game.draw(g);
		
		Color saved = g.getColor();
		g.setColor(Color.WHITE);
		g.fillRect(Game.WIDTH / 2, -1, 3, Game.HEIGHT + 20);
		g.setColor(saved);
	}
	
	private void drawScore(Graphics g) {
		score.draw(g);
	}
	
	private void gameOver(Graphics g) {
		Color saved = g.getColor();
		g.setColor(new Color(0, 0, 0));
		g.setFont(new Font("DialogInput", 20, 20));
		FontMetrics fm = g.getFontMetrics();
		centreString(OVER, g, fm, Game.HEIGHT / 2);
		centreString(REPLAY, g, fm, Game.HEIGHT / 2 + 50);
		g.setColor(saved);
	}
	
	private void centreString(String str, Graphics g, FontMetrics fm, int yPos) {
		int width = fm.stringWidth(str);
		g.drawString(str, (Game.WIDTH - width) / 2, yPos);
	}
}
